package com.dragon.modules.yuegou.client.ali.client.impl;

import com.dragon.modules.yuegou.client.ali.client.CheckBankNoClient;
import com.dragon.modules.yuegou.client.ali.response.CardDetailResponse;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;

import java.io.IOException;
import java.io.UncheckedIOException;

@Slf4j
@Service
public class CheckBankNoClientImpl implements CheckBankNoClient {
    private WebClient client = WebClient.create("https://ccdcapi.alipay.com");
    private ObjectMapper objectMapper;

    public CheckBankNoClientImpl(){
        objectMapper = new ObjectMapper();
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    }

    public CardDetailResponse checkCardDetail(String cardNo){
        String text = client.get()
                .uri(b -> b.path("/validateAndCacheCardInfo.json")
                        .queryParam("_input_charset", "utf-8")
                        .queryParam("cardNo", cardNo)
                        .queryParam("cardBinCheck", true)
                        .build())
                .accept(MediaType.APPLICATION_JSON_UTF8)
                .exchange()
                .flatMap(res -> res.bodyToMono(String.class))
                .block();
        log.debug("jscode2session : {}", text);
        try {
            return objectMapper.readerFor(CardDetailResponse.class).readValue(text);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
}
